<?php
namespace app\common\model;

use hema\alipay\Driver as Alipay;
use hema\wechat\Wxapp;
use hema\wechat\Wechat;
use think\facade\Cache;

/**
 * 站点设置模型
 */
class Setting extends BaseModel
{
    // 定义表名
    protected $name = 'setting';
    protected $createTime = false;
    // 追加字段
    protected $append = [];
    
    /**
     * 设置项描述
     */
    private $describe = [
        'base' => '站点设置',
        'sms' => '短信平台',
        'passport' => '登录注册',
        'map' => '地图设置',
		'wxtpl' => '微信模板消息',
        'wechat' => '微信公众号',
        'subscribe' => '关注回复',//公众号
        'menus' => '公众号菜单',
		'wxapp' => '微信小程序',
		'wxpay' => '微信支付',
		'aliapp' => '支付宝小程序',
		'aliweb' => '支付宝网页应用',
		'vip' => '会员卡设置',
        'sign' => '签到设置',
        'recharge' => '充值设置',
        'delivery' => '配送设置',
        'cash' => '提现设置',//站点设置
		'goods' => '商品设置',
		'wifi' => 'WiFi设置',
		'trade' => '交易设置',
        'wxapptpl' => '微信小程序订阅消息',
        
		
    ];

    /**
     * 获取器: 转义数组格式
     */
    public function getValuesAttr($value)
    {
        return json_decode($value, true);
    }

    /**
     * 修改器: 转义成json格式
     */
    public function setValuesAttr($value)
    {
        return json_encode($value);
    }

    /**
     * 获取指定项设置
     */
    public static function getItem(string $key,$developer_id=0)
    {
        $data = self::getAll($developer_id);
        return isset($data[$key]) ? $data[$key]['values'] : [];
    }

    /**
     * 获取设置项信息
     */
    public static function detail(string $key,$developer_id=0)
    {
        // 筛选条件
        $filter = [
			'key' => $key,
			'developer_id' => $developer_id
		];
        return self::where($filter)->find();
    }

    /**
     * 全局缓存: 系统设置
     */
    public static function getAll($developer_id)
    {
        $self = new static;
        if (!$data = Cache::get('setting_'.$developer_id)) {
            $data = array_column($self::where('developer_id',$developer_id)->select()->toArray(), null, 'key');
            Cache::set('setting_'.$developer_id, $data);
        }
        return array_merge_multiple($self->defaultData(), $data);
    }

    /**
     * 更新系统设置
     */
    public function edit(string $key, array $values,$developer_id=0)
    {
        //如果是设置微信小程序订阅消息
        if($key == 'wxapptpl'){
            if(!$values = $this->wxapptpl($values)){
                return false;
            }
        }
        //公众号菜单
        if($key == 'menus'){
            $wx = new Wechat;
            if(!$wx->creatMenu($values)){
                $this->error = $wx->getError();
                return false;
            }
        }
        //关注公众号回复
        if($key == 'subscribe'){
            $values = $this->subscribe($values);
        }
        $model = self::detail($key,$developer_id) ?: $this;
        // 删除系统设置缓存
        Cache::delete('setting_'.$developer_id);
        return $model->save([
            'key' => $key,
            'describe' => $this->describe[$key],
            'values' => $values,
			'developer_id' => $developer_id
        ]) !== false;
    }
    
    /**
     * 关注回复内容
     */
    private function subscribe($data)
    {
        if($data['type']['value'] != 'text'){
            if(!$material = Material::mediaId($data['content']['media_id'])){
                $this->error = '素材不存在';
                return false; 
            }
            //视频消息
            if($data['type']['value'] == 'video'){
                //获取视频素材内容
                $data['content']['title'] = $material['name'];
                $data['content']['description'] = $material['introduction'];
            }
            //图文消息
            if($data['type']['value'] == 'news'){
                $data['content']['article_count'] = sizeof($material['text']);
                $item = [];
                foreach ($material['text'] as $vo){
                    $item[] = [
                        'title' => $vo['title'],
                        'description' => $vo['digest'],
                        'pic_url' => $vo['url'],
                        'url' => $vo['content_source_url'],
                    ];
                }
                $data['content']['articles'] = $item;
            }
        }
        return $data;
    }

    /**
     * 餐饮微信订阅消息设置
     */
    private function wxapptpl(array $values)
    {
        $wx = new Wxapp;
        //获取已设置的服务类目
        if(!$result = $wx->getCategory()){
            $this->error = $wx->getError();
            return false;
        }
        $isSet = false;//是否符合设置要求
        //验证是否添加指定的服务类目录
        foreach ($result['data'] as $item){
            //1273类目 = 商业服务- 软件/建站/技术开发
            if($item['id']==1273){
                $isSet = true;
                break;
            }
        }
        if(!$isSet){
            $this->error = '配置失败：该小程序未添加“商业服务-软件/建站/技术开发”服务类目，或未通过审核';
            return false;
        }
        //获取帐号下的模板列表
        if(!$result = $wx->getMessageTemplateList()){
            $this->error = $wx->getError();
            return false;
        }
        //循环删除订阅消息模板
        foreach ($result['data'] as $item){
            if(!$wx->deleteMessageTemplate($item['priTmplId'])){
                $this->error = $wx->getError();
                return false;
            }
        }
        
        //添加商家接单通知
        $tid = '31781';
        //1商家名称，2订单状态，3接单时间
        $kidlist = [1,2,3];
        $desc ='商家接单通知';
        if(!$result = $wx->addMessageTemplate($tid,$kidlist,$desc)){
            $this->error = $wx->getError();
            return false;
        }
        $values['receive'] = $result['priTmplId'];
        
        //添加骑手取货通知
        $tid = '31780';
        //1商家名称、2订单状态、3接单时间
        $kidlist = [1,2,3];
        $desc ='骑手接单通知';
        if(!$result = $wx->addMessageTemplate($tid,$kidlist,$desc)){
            $this->error = $wx->getError();
            return false;
        }
        $values['horseman'] = $result['priTmplId'];
        
        //订单配送通知
        $tid = '31339';
        //8商家名称 9订单状态 5配送人、6配送电话 10送出时间
        $kidlist = [8,9,5,6,10];
        $desc ='订单配送通知';
        if(!$result = $wx->addMessageTemplate($tid,$kidlist,$desc)){
            $this->error = $wx->getError();
            return false;
        }
        $values['delivery'] = $result['priTmplId'];
        
        //提货通知
        $tid = '30804';
        //3提货门店、2状态、6提货码、9提货地点、7联系电话
        $kidlist = [3,2,6,9,7];
        $desc ='提货通知';
        if(!$result = $wx->addMessageTemplate($tid,$kidlist,$desc)){
            $this->error = $wx->getError();
            return false;
        }
        $values['take'] = $result['priTmplId'];
        //退款状态通知
        $tid = '31441';
        //8订单编号、9退款金额、4退款状态、5备注、
        $kidlist = [8,9,4,5];
        $desc ='退款状态通知';
        if(!$result = $wx->addMessageTemplate($tid,$kidlist,$desc)){
            $this->error = $wx->getError();
            return false;
        }
        $values['refund'] = $result['priTmplId'];
        return $values;
    }

    /**
     * 默认配置
     */
    public function defaultData()
    {
        return [
            'base' => [
                'key' => 'base',
                'describe' => '基本设置',
                'values' => [
                    'name' => '河马点单',//网站名称
                    'company' => '',//公司名称
                    'phone' => '',//联系电话
                    'icp' => '',    //备案号
                ],
            ],
            'map' => [
                'key' => 'map',
                'describe' => '地图设置',
                'values' => [
                    'gateway' => '',     //地图平台
                ]
            ],
            'delivery' => [
                'key' => 'delivery',
                'describe' => '配送设置',
                'values' => [
                    'delivery_range' => '10000', //配送范围
                    'min_range' => '2000',        //起步范围
                    'min_price' => '3',        //起步价格
                    'inc_range' => '500',//递增范围
                    'inc_price' => '1',//递增单价
                ]
            ],
            'passport' => [
                'key' => 'passport',
                'describe' => '登录注册',
                'values' => [
                    'login' => [
                        'wechat' => 0,//关注微信公众号
                        'phone' => 0,//手机验证码
                        'user_name' => 1,//账号密码
                    ],
                    'register' => [
                        'is_open' => 0,//是否开启注册
                    ],
                ],
            ],
            'wechat' => [
                'key' => 'wechat',
                'describe' => '微信公众号',
                'values' => [
                    'app_id' => '', //AppID
                    'app_secret' => '',//AppSecret
                    'url' => base_url() . 'admin/task/wechat',//服务器地址(URL)
                    'token' => '',//令牌(Token)
                    'encoding_aes_key' => '',//消息加解密密钥EncodingAESKey
                ]
            ],
            'subscribe' => [
                'key' => 'subscribe',
                'describe' => '关注回复',
                'values' => [
                    'is_open' => [
                        'value' => 1,//是否开启 0=关闭，1=开启
                    ], 
                    'type' => [
                        'value' => 'text', //消息类型 text=文字消息,image=图片消息,news=图文消息,voice=声音消息  
                    ],
                    'content' => [
                        'text' => '感谢您的关注！',//回复文字
                        'media_id' => '',//素材
                    ]
                ]
            ],
            'menus' => [
                'key' => 'menus',
                'describe' => '公众号菜单',
                'values' => [
                /*  0 => [
                        "type" => "view",
                        "name" => "一级菜单",
                        "sub_button" => [
                            0 => [
                                "type" => "click",
                                "name" => "二级菜单",
                                "key" => "关键字"
                            ],
                        ],
                        "url" => base_url()
                    ]*/
                ],
            ],
			'wxapp' => [
			    'key' => 'wxapp',
			    'describe' => '微信小程序',
			    'values' => [
			        'app_id' => '',//小程序ID
			        'app_secret' => '',//小程序密钥
			    ]
			],
            'wxpay' => [
                'key' => 'wxpay',
                'describe' => '微信支付',
                'values' => [
                    'mch_id' => '',//商户号
                    'api_key' => '', //APIv3密钥
                    'api_serial_no' => '',//API证书序列号
                    'cert_pem' => '', //apiclient_cert.pem 证书
                    'key_pem' => '', //apiclient_key.pem 密钥
                    'serial_no' => '',//平台证书序列号
                    'certificates' => '',//平台证书
                    'expire_time' => 0,//平台证书到期时间
                ]
            ],
            'aliapp' => [
                'key' => 'aliapp',
                'describe' => '支付宝小程序',
                'values' => [
                    'app_id' => '', //APPID
                    'aes_key' => '',//AES密钥
                    'app_private_key' => '', //应用私钥
                    'alipay_public_key' => '',//支付宝公钥
                ],
            ],
            'aliweb' => [
                'key' => 'aliweb',
                'describe' => '支付宝网页应用',
                'values' => [
                    'app_id' => '', //APPID
                    'app_private_key' => '', //应用私钥
                ]
            ],
            'wxtpl' => [
                'key' => 'wxtpl',
                'describe' => '微信模板消息',
                'values' => [
                    'news_order' => '',//新订单通知
                    'register_success' => '',//注册成功通知
                    'apply_refund' => '',  //用户申请退款通知
                    'cash_account' => '',  //提现到账通知
                    'apply_cash' => '',  //提现申请通知
                ],
            ],
            'sms' => [
                'key' => 'sms',
                'describe' => '短信平台',
                'values' => [
                    'gateway' => '',     //短信平台
                    'scene' => [
                        'captcha' => 0,//验证码
                    ]
                ]
            ],
            'vip' => [
                'key' => 'vip',
                'describe' => '会员卡设置',
                'values' => [
                    'is_open' => 1,//是否开启
                    'buy_price' => 0,//购买价格
                    'expire_time' => 0,//1一年 0终身，
                    'vip' => [
                        0 => [
                            'card_cover' => base_url() . 'assets/img/vip/v1.png',
                            'name' => 'V1',
                            'discount' => 0,//等级折扣
                            'score' => 0,//所需积分
                            'free_delivery' => 0,//是否免配送费
                            'gift' => []
                        ],
                        1 => [
                            'card_cover' => base_url() . 'assets/img/vip/v2.png',
                            'name' => 'V2',
                            'discount' => 95,//等级折扣
                            'score' => 500, 
                            'free_delivery' => 0,//是否免配送费
                            'gift' => []
                        ],
                        2 => [
                            'card_cover' => base_url() . 'assets/img/vip/v3.png',
                            'name' => 'V3',
                            'discount' => 90,//等级折扣
                            'score' => 1000, 
                            'free_delivery' => 0,//是否免配送费
                            'gift' => []
                        ],
                        3 => [
                            'card_cover' => base_url() . 'assets/img/vip/v4.png',
                            'name' => 'V4',
                            'discount' => 85,//等级折扣
                            'score' => 2000, 
                            'free_delivery' => 0,//是否免配送费
                            'gift' => []
                        ],
                        4 => [
                            'card_cover' => base_url() . 'assets/img/vip/v5.png',
                            'name' => 'V5',
                            'discount' => 80,//等级折扣
                            'score' => 5000, 
                            'free_delivery' => 0,//是否免配送费
                            'gift' => []
                        ], 
                        5 => [
                            'card_cover' => base_url() . 'assets/img/vip/v6.png',
                            'name' => 'V6',
                            'discount' => 75,//等级折扣
                            'score' => 10000,//所需积分
                            'free_delivery' => 0,//是否免配送费
                            'gift' => []
                        ],
                    ]
                ],
            ],
           'sign' => [
                'key' => 'sign',
                'describe' => '签到设置',
                'values' => [
                    'type' => 'score',//奖励类型 score=积分，money=余额
                    'mode' => 'fixed',//奖励模式 fixed=固定，random=随机
                    'number' => 1,//
                    'plan' => [
                        /*0 => [
                            'days' => 15,//连续天数
                            'number' => 10,//额外奖励
                            'type' => 'score',//奖励类型
                        ],*/
                    ],
                    'describe' => '1. 每次签到赠送1积分
2. 连续签到15天，额外赠送10积分
3. 连续签到30天，额外赠送40积分', //签到说明
                ],
            ],
            'recharge' => [
                'key' => 'recharge',
                'describe' => '充值设置',
                'values' => [
                    'is_open' => 1,     //是否开启
                    'is_custom' => 1,   //是否允许用户自定义金额
                    'describe' => '1. 账户充值仅限微信在线支付方式，充值金额实时到账
2. 账户充值套餐赠送的金额即时到账
3. 账户余额有效期：自充值日起至用完即止
4. 储值金额不可提现、不计利息、不可转赠', //充值说明
                ],
            ],
            'cash' => [
                'key' => 'cash',
                'describe' => '提现设置',
                'values' => [
                    'is_open' => 1,     //是否开启
                    'is_hundred' => 1,   //是否整百
                    'describe' => '1. 提现规则第一条
2. 提现规则第二条
3. 提现规则第三条
4. 提现规则第四条', //提现说明
                ],
            ],
        ];
    }
}
